"use client";

import React, { useEffect, useRef, useState, useMemo } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

// 简约高还原并支持伸缩的数据库表侧边栏组件
export default function TableSider({
  isDarkMode,
  isVisible = true,
  onTableClick,
}) {
  // 侧边栏宽度（可拖拽调整）
  const MIN_WIDTH = 240;
  const MAX_WIDTH = 520;
  const DEFAULT_WIDTH = 320;
  const [width, setWidth] = useState(DEFAULT_WIDTH);
  const [isResizing, setIsResizing] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const startXRef = useRef(0);
  const startWidthRef = useRef(DEFAULT_WIDTH);
  const siderRef = useRef(null);

  // 模拟数据库表数据
  const [tables] = useState([
    {
      id: 1,
      name: "t_auth_cert",
      size: "16KB",
      desc: "",
      fields: [
        {
          name: "id",
          type: "INT",
          size: "11",
          nullable: false,
          key: "PRI",
          comment: "主键ID",
        },
        {
          name: "user_id",
          type: "VARCHAR",
          size: "50",
          nullable: false,
          key: "",
          comment: "用户唯一标识",
        },
        {
          name: "cert_type",
          type: "VARCHAR",
          size: "20",
          nullable: false,
          key: "",
          comment: "证件类型",
        },
        {
          name: "cert_data",
          type: "TEXT",
          size: "",
          nullable: true,
          key: "",
          comment: "证件内容",
        },
        {
          name: "created_at",
          type: "TIMESTAMP",
          size: "",
          nullable: false,
          key: "",
          comment: "创建时间",
        },
      ],
    },
    {
      id: 2,
      name: "t_db",
      size: "32KB",
      desc: "",
      fields: [
        {
          name: "id",
          type: "INT",
          size: "11",
          nullable: false,
          key: "PRI",
          comment: "主键ID",
        },
        {
          name: "db_name",
          type: "VARCHAR",
          size: "100",
          nullable: false,
          key: "UNI",
          comment: "数据库名（唯一）",
        },
        {
          name: "db_type",
          type: "VARCHAR",
          size: "20",
          nullable: false,
          key: "",
          comment: "数据库类型",
        },
        {
          name: "host",
          type: "VARCHAR",
          size: "255",
          nullable: false,
          key: "",
          comment: "主机地址",
        },
        {
          name: "port",
          type: "INT",
          size: "5",
          nullable: false,
          key: "",
          comment: "端口号",
        },
        {
          name: "username",
          type: "VARCHAR",
          size: "50",
          nullable: false,
          key: "",
          comment: "连接用户名",
        },
        {
          name: "password",
          type: "VARCHAR",
          size: "255",
          nullable: false,
          key: "",
          comment: "连接密码",
        },
      ],
    },
    {
      id: 3,
      name: "t_db_instance",
      size: "16KB",
      desc: "",
      fields: [
        {
          name: "id",
          type: "INT",
          size: "11",
          nullable: false,
          key: "PRI",
          comment: "主键ID",
        },
        {
          name: "instance_name",
          type: "VARCHAR",
          size: "100",
          nullable: false,
          key: "",
          comment: "实例名称",
        },
        {
          name: "db_id",
          type: "INT",
          size: "11",
          nullable: false,
          key: "FK",
          comment: "数据库ID（外键）",
        },
        {
          name: "status",
          type: "ENUM",
          size: "",
          nullable: false,
          key: "",
          comment: "状态枚举",
        },
      ],
    },
    {
      id: 4,
      name: "t_sys_log",
      size: "1.7MB",
      desc: "",
      fields: [
        {
          name: "id",
          type: "BIGINT",
          size: "20",
          nullable: false,
          key: "PRI",
          comment: "日志主键",
        },
        {
          name: "user_id",
          type: "INT",
          size: "11",
          nullable: false,
          key: "FK",
          comment: "用户ID（外键）",
        },
        {
          name: "action",
          type: "VARCHAR",
          size: "100",
          nullable: false,
          key: "",
          comment: "操作行为",
        },
        {
          name: "ip_address",
          type: "VARCHAR",
          size: "45",
          nullable: true,
          key: "",
          comment: "来源IP",
        },
        {
          name: "user_agent",
          type: "TEXT",
          size: "",
          nullable: true,
          key: "",
          comment: "UA信息",
        },
        {
          name: "created_at",
          type: "TIMESTAMP",
          size: "",
          nullable: false,
          key: "",
          comment: "创建时间",
        },
      ],
    },
    {
      id: 5,
      name: "t_sys_m",
      size: "16KB",
      desc: "t_sys_log | 系统操作日志",
      fields: [
        {
          name: "id",
          type: "INT",
          size: "11",
          nullable: false,
          key: "PRI",
          comment: "主键ID",
        },
        {
          name: "module_name",
          type: "VARCHAR",
          size: "50",
          nullable: false,
          key: "",
          comment: "模块名称",
        },
        {
          name: "operation",
          type: "VARCHAR",
          size: "100",
          nullable: false,
          key: "",
          comment: "操作名称",
        },
        {
          name: "result",
          type: "TEXT",
          size: "",
          nullable: true,
          key: "",
          comment: "操作结果",
        },
      ],
    },
  ]);

  // 根据搜索查询过滤表格
  const filteredTables = useMemo(() => {
    if (!searchQuery.trim()) return tables;

    return tables.filter((table) => {
      // 搜索表名
      const nameMatch = table.name
        .toLowerCase()
        .includes(searchQuery.toLowerCase());
      // 搜索字段名
      const fieldMatch = table.fields.some(
        (field) =>
          field.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          field.comment.toLowerCase().includes(searchQuery.toLowerCase())
      );
      return nameMatch || fieldMatch;
    });
  }, [tables, searchQuery]);

  // 拖拽事件绑定
  useEffect(() => {
    if (!isResizing) return;
    const onMove = (e) => {
      const dx = e.clientX - startXRef.current;
      let next = startWidthRef.current + dx;
      if (next < MIN_WIDTH) next = MIN_WIDTH;
      if (next > MAX_WIDTH) next = MAX_WIDTH;
      setWidth(next);
    };
    const onUp = () => {
      setIsResizing(false);
    };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
    };
  }, [isResizing]);

  const handleResizeStart = (e) => {
    e.preventDefault();
    startXRef.current = e.clientX;
    startWidthRef.current = width;
    setIsResizing(true);
  };
  const handleResizeDoubleClick = () => setWidth(DEFAULT_WIDTH);

  const typeClass = (t) => {
    const map = {
      INT: "type-primary",
      BIGINT: "type-primary",
      VARCHAR: "type-success",
      TEXT: "type-info",
      TIMESTAMP: "type-warning",
      ENUM: "type-secondary",
    };
    return map[t] || "type-light";
  };

  if (!isVisible) {
    return null;
  }

  return (
    <aside
      ref={siderRef}
      className={`sider ${isResizing ? "resizing" : ""} ${
        isDarkMode ? "dark" : "light"
      }`}
      style={{ width }}
    >
      <div className="sider-header">
        <span className="sider-title">数据库表</span>
        <span className="sider-sub">共 {filteredTables.length} 个</span>
      </div>

      {/* 搜索栏 */}
      <div className="search-container">
        <div className="input-group input-group-sm">
          <div className="input-group-prepend">
            <span className="input-group-text search-icon">🔍</span>
          </div>
          <input
            type="text"
            className="form-control search-input"
            placeholder="搜索表或字段..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
          {searchQuery && (
            <div className="input-group-append">
              <button
                className="btn btn-outline-secondary clear-btn"
                type="button"
                onClick={() => setSearchQuery("")}
              >
                ✕
              </button>
            </div>
          )}
        </div>
      </div>

      {/* 表格列表 */}
      <div className="sider-list">
        {filteredTables.length === 0 ? (
          <div className="no-results">
            <div className="no-results-text">未找到匹配的表或字段</div>
          </div>
        ) : (
          filteredTables.map((t) => (
            <TableItem
              key={t.id}
              table={t}
              typeClass={typeClass}
              isDarkMode={isDarkMode}
              searchQuery={searchQuery}
              onTableClick={onTableClick}
            />
          ))
        )}
      </div>

      {/* 右侧拖拽手柄 */}
      <div
        className="sider-resizer"
        onMouseDown={handleResizeStart}
        onDoubleClick={handleResizeDoubleClick}
        title="拖动调整宽度，双击重置"
      />

      <style jsx>{`
        .sider {
          position: relative;
          height: 100vh;
          overflow-y: auto;
          min-width: ${MIN_WIDTH}px;
          max-width: ${MAX_WIDTH}px;
          transition: background-color 0.3s ease, border-color 0.3s ease,
            transform 0.3s ease;
        }

        .sider.light {
          background: #fff;
          border-right: 1px solid #eee;
        }

        .sider.dark {
          background: #2d2d2d;
          border-right: 1px solid #404040;
        }

        .resizing {
          user-select: none;
          cursor: col-resize;
        }

        .sider-header {
          padding: 14px 16px;
          display: flex;
          align-items: baseline;
          justify-content: space-between;
          transition: border-color 0.3s ease;
        }

        .sider.light .sider-header {
          border-bottom: 1px solid #eee;
        }

        .sider.dark .sider-header {
          border-bottom: 1px solid #404040;
        }

        .sider-title {
          font-weight: 600;
        }

        .sider.light .sider-title {
          color: #222;
        }

        .sider.dark .sider-title {
          color: #fff;
        }

        .sider-sub {
          font-size: 12px;
        }

        .sider.light .sider-sub {
          color: #888;
        }

        .sider.dark .sider-sub {
          color: #aaa;
        }

        .search-container {
          padding: 12px 16px;
          border-bottom: 1px solid;
        }

        .sider.light .search-container {
          border-color: #f0f0f0;
        }

        .sider.dark .search-container {
          border-color: #404040;
        }

        .search-icon {
          font-size: 14px;
          transition: background-color 0.3s ease, border-color 0.3s ease,
            color 0.3s ease;
        }

        .sider.light .search-icon {
          background: #f6f6f6;
          border-color: #e9e9e9;
          color: #666;
        }

        .sider.dark .search-icon {
          background: #404040;
          border-color: #555;
          color: #aaa;
        }

        .search-input {
          transition: background-color 0.3s ease, border-color 0.3s ease,
            color 0.3s ease;
        }

        .sider.light .search-input {
          background: #fff;
          border-color: #e9e9e9;
          color: #333;
        }

        .sider.dark .search-input {
          background: #333;
          border-color: #555;
          color: #fff;
        }

        .sider.light .search-input::placeholder {
          color: #999;
        }

        .sider.dark .search-input::placeholder {
          color: #aaa;
        }

        .clear-btn {
          font-size: 12px;
          padding: 0.25rem 0.5rem;
          transition: all 0.2s ease;
        }

        .sider.light .clear-btn {
          color: #666;
          border-color: #e9e9e9;
        }

        .sider.dark .clear-btn {
          color: #aaa;
          border-color: #555;
          background: #404040;
        }

        .sider.light .clear-btn:hover {
          background: #f8f9fa;
          border-color: #ddd;
        }

        .sider.dark .clear-btn:hover {
          background: #555;
          border-color: #666;
        }

        .sider-list {
          display: block;
        }

        .no-results {
          padding: 40px 20px;
          text-align: center;
        }

        .no-results-text {
          font-size: 14px;
          transition: color 0.3s ease;
        }

        .sider.light .no-results-text {
          color: #999;
        }

        .sider.dark .no-results-text {
          color: #aaa;
        }

        .sider-resizer {
          position: absolute;
          top: 0;
          right: 0;
          width: 6px;
          height: 100%;
          cursor: col-resize;
          background: transparent;
        }

        .sider-resizer:hover {
          background: rgba(0, 0, 0, 0.04);
        }

        .sider.dark .sider-resizer:hover {
          background: rgba(255, 255, 255, 0.1);
        }
      `}</style>
    </aside>
  );
}

// 单个表项（拆分以保持主组件简洁）
function TableItem({
  table,
  typeClass,
  isDarkMode,
  searchQuery,
  onTableClick,
}) {
  const [isOpen, setIsOpen] = useState(false);
  const [active, setActive] = useState(false);
  const toggle = () => {
    setIsOpen((v) => !v);
    setActive(true);
  };

  // 高亮搜索关键词
  const highlightText = (text, query) => {
    if (!query.trim()) return text;

    const regex = new RegExp(
      `(${query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`,
      "gi"
    );
    const parts = text.split(regex);

    return parts.map((part, index) =>
      regex.test(part) ? (
        <span key={index} className="highlight">
          {part}
        </span>
      ) : (
        part
      )
    );
  };

  return (
    <div
      className={`item ${active ? "active" : ""} ${
        isDarkMode ? "dark" : "light"
      }`}
    >
      <button className="item-row" onClick={toggle} aria-expanded={isOpen}>
        <span className={`chev ${isOpen ? "down" : ""}`}>▸</span>
        <img src="/file.svg" alt="file" className="file-icon" />
        <div className="item-main">
          <div
            className="item-name clickable-table-name"
            onClick={(e) => {
              e.stopPropagation(); // 阻止冒泡到父级按钮
              if (onTableClick) {
                onTableClick(table.name);
              }
            }}
            title={`点击生成查询 ${table.name} 的SQL语句`}
          >
            {highlightText(table.name, searchQuery)}
          </div>
          {table.desc && (
            <div className="item-desc">
              {highlightText(table.desc, searchQuery)}
            </div>
          )}
        </div>
        <div className="item-right">
          <span className="size-text">{table.size}</span>
          <span className="count-badge">{table.fields.length}</span>
        </div>
      </button>

      {isOpen && (
        <div className="field-panel">
          <div className="field-head">字段（名称 | 注释）</div>
          {table.fields.map((f, i) => (
            <div className="field-row" key={i}>
              <div className="field-line">
                <div className="field-left">
                  {highlightText(f.name, searchQuery)}
                  {!f.nullable && <span className="req">*</span>}
                </div>
                <div className="field-right" title={f.comment || ""}>
                  {highlightText(f.comment || "-", searchQuery)}
                </div>
              </div>
              <div className="chips">
                <span className={`chip ${typeClass(f.type)}`}>
                  {f.type}
                  {f.size ? `(${f.size})` : ""}
                </span>
                {f.key && (
                  <span className="chip chip-outline">
                    {f.key === "PRI"
                      ? "PRIMARY"
                      : f.key === "FK"
                      ? "FOREIGN"
                      : f.key}
                  </span>
                )}
                {f.nullable ? (
                  <span className="chip chip-outline">NULL</span>
                ) : (
                  <span className="chip chip-outline">NOT NULL</span>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      <style jsx>{`
        .item {
          transition: border-color 0.3s ease;
        }

        .item.light {
          border-bottom: 1px solid #f1f1f1;
        }

        .item.dark {
          border-bottom: 1px solid #353535;
        }

        .item.light.active .item-row {
          background: #f8f9fa;
        }

        .item.dark.active .item-row {
          background: #404040;
        }

        .item-row {
          width: 100%;
          display: flex;
          align-items: center;
          padding: 10px 12px;
          background: transparent;
          border: 0;
          outline: none;
          cursor: pointer;
          transition: background-color 0.2s ease;
        }

        .item.light .item-row:hover {
          background: #fafafa;
        }

        .item.dark .item-row:hover {
          background: #383838;
        }

        .file-icon {
          width: 16px;
          height: 16px;
          margin: 0 8px;
          opacity: 0.8;
        }

        .chev {
          width: 14px;
          display: inline-block;
          margin-right: 4px;
          transition: transform 0.2s ease, color 0.3s ease;
        }

        .item.light .chev {
          color: #999;
        }

        .item.dark .chev {
          color: #aaa;
        }

        .chev.down {
          transform: rotate(90deg);
        }

        .item-main {
          flex: 1;
          min-width: 0;
        }

        .item-name {
          font-size: 14px;
          line-height: 1.3;
          transition: color 0.3s ease;
        }

        .clickable-table-name {
          cursor: pointer;
          border-radius: 3px;
          padding: 2px 4px;
          margin: -2px -4px;
          transition: all 0.2s ease;
        }

        .clickable-table-name:hover {
          color: #007bff !important;
        }

        .item.light .item-name {
          color: #333;
        }

        .item.dark .item-name {
          color: #fff;
        }

        .item-desc {
          font-size: 12px;
          transition: color 0.3s ease;
        }

        .item.light .item-desc {
          color: #777;
        }

        .item.dark .item-desc {
          color: #bbb;
        }

        .item-right {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .size-text {
          font-size: 12px;
          transition: color 0.3s ease;
        }

        .item.light .size-text {
          color: #999;
        }

        .item.dark .size-text {
          color: #aaa;
        }

        .count-badge {
          border-radius: 10px;
          padding: 2px 8px;
          font-size: 12px;
          transition: background-color 0.3s ease, color 0.3s ease;
        }

        .item.light .count-badge {
          background: #e9ecef;
          color: #555;
        }

        .item.dark .count-badge {
          background: #555;
          color: #ccc;
        }

        .field-panel {
          padding: 6px 12px 10px 32px;
          transition: background-color 0.3s ease, border-color 0.3s ease;
        }

        .item.light .field-panel {
          background: #fcfcfc;
          border-top: 1px solid #f0f0f0;
        }

        .item.dark .field-panel {
          background: #333;
          border-top: 1px solid #404040;
        }

        .field-head {
          font-size: 12px;
          margin: 4px 0 6px;
          transition: color 0.3s ease;
        }

        .item.light .field-head {
          color: #999;
        }

        .item.dark .field-head {
          color: #aaa;
        }

        .field-row {
          padding: 6px 0;
        }

        .field-line {
          display: flex;
          align-items: baseline;
          justify-content: space-between;
          gap: 12px;
        }

        .field-left {
          font-size: 13px;
          transition: color 0.3s ease;
        }

        .item.light .field-left {
          color: #222;
        }

        .item.dark .field-left {
          color: #fff;
        }

        .field-right {
          font-size: 12px;
          flex: 0 0 auto;
          max-width: 50%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          transition: color 0.3s ease;
        }

        .item.light .field-right {
          color: #666;
        }

        .item.dark .field-right {
          color: #bbb;
        }

        .req {
          color: #d9534f;
          margin-left: 4px;
        }

        .chips {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          justify-content: flex-start;
          margin-top: 6px;
        }

        .chip {
          border-radius: 10px;
          padding: 2px 8px;
          font-size: 12px;
          color: #fff;
        }

        .chip-outline {
          background: transparent;
          color: #555;
          transition: border-color 0.3s ease, color 0.3s ease;
        }

        .item.light .chip-outline {
          border: 1px solid #ced4da;
          color: #555;
        }

        .item.dark .chip-outline {
          border: 1px solid #666;
          color: #ccc;
        }

        .type-primary {
          background: #0d6efd;
        }
        .type-success {
          background: #28a745;
        }
        .type-info {
          background: #17a2b8;
        }
        .type-warning {
          background: #ffc107;
          color: #333;
        }
        .type-secondary {
          background: #6c757d;
        }
        .type-light {
          background: #adb5bd;
        }

        .highlight {
          background-color: #ffeb3b;
          color: #333;
          padding: 1px 2px;
          border-radius: 2px;
          font-weight: 500;
        }

        .item.dark .highlight {
          background-color: #ffc107;
          color: #000;
        }
      `}</style>
    </div>
  );
}
